package com.nb.camerademo;

import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import androidx.annotation.RequiresApi;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author Administrator on 2024-05-23.
 * <p>
 * 站在顶峰 看世界
 * 落到谷底 思人生
 */
public class ImageSaver  implements Runnable {

    private Image mImage;
    private File mFile;

    public ImageSaver(Image image) {
        this.mImage = image;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void run() {
        ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        FileOutputStream output = null;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
        String fname = "IMG_" + sdf.format(new Date()) + ".jpg";
        mFile = new File(BaseApp.getApp().getExternalFilesDir(null), fname);

        try {
            output = new FileOutputStream(mFile);
            output.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            mImage.close();
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 把file里面的图片插入到系统相册中
        try {
            MediaStore.Images.Media.insertImage(BaseApp.getApp().getContentResolver(),
                    mFile.getAbsolutePath(), fname, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 通知相册更新
        BaseApp.getApp().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(mFile)));
    }
}